from flask import current_app, g, request, jsonify
from info import constants, db
from info.libs.qiniu.image_storage import storage
from info.models import Area, House, Facility, HouseImage
from info.response_code import RET
from info.utils.common import user_login
from . import new_house_blu


@new_house_blu.route('/api/v1.0/houses',methods=["POST"])
@user_login
def new_house():
    user_id = g.user.id

    title = request.json.get("title")  # 房屋名称标题
    price = request.json.get("price")  # 房屋单价
    area_id = request.json.get("area_id")  # 房屋所属城区的编号
    address = request.json.get("address")  # 房屋地址
    room_count = request.json.get("room_count")  # 房屋包含的房间数目
    acreage = request.json.get("acreage")  # 房屋面积
    unit = request.json.get("unit")  # 房屋布局（几室几厅)
    capacity = request.json.get("capacity")  # 房屋容纳人数
    beds = request.json.get("beds")  # 房屋卧床数目
    deposit = request.json.get("deposit")  # 押金
    min_days = request.json.get("min_days")  # 最小入住天数
    max_days = request.json.get("max_days")  # 最大入住天数
    facility_ids = request.json.get("facility")

    if not all([title, price, area_id, address, room_count, acreage,
                unit, capacity, beds, deposit, min_days, max_days, facility_ids]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    try:
        price = int(float(price) * 100)
        deposit = int(float(deposit) * 100)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        area = Area.query.get(area_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 通过Facility类中的id值使用in_方法查询其中的id
    # select * from ih_facility_info where id in facility_ids;
    try:
        facilities = Facility.query.filter(Facility.id.in_(facility_ids)).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if not facilities:
        return jsonify(errno=RET.DBERR, errmsg="没有对应设施")

    # 创建实例对象
    house = House()
    house.user_id=user_id
    house.title=title
    house.price=int(price) * 100  # 需要转化成整数
    house.area_id=area_id,
    house.address=address
    house.room_count=room_count
    house.acreage=acreage
    house.unit=unit
    house.capacity=capacity
    house.beds=beds
    house.deposit=deposit
    house.min_days=min_days
    # house.max_days = max_days if max_days != '0' else 9999
    house.max_days = max_days
    house.facilities = facilities

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据异常")

    return jsonify(errno=RET.OK, errmsg="OK", data={"house_id": house.id})


@new_house_blu.route("/api/v1.0/houses/<int:house_id>/images", methods=["POST"])
@user_login
def save_house_image(house_id):
    """保存房屋图片"""
    image_file = request.files.get("house_image")
    house_id = request.form.get("house_id")

    if not all([image_file, house_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if house is None:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    image_data = image_file.read()
    try:
        file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")
    # 上传首页图片
    if not house.index_image_url:
        house.index_image_url = file_name
    # 上传详情页图片
    house_image = HouseImage()
    house_image.house_id = house_id
    house_image.url = file_name

    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存图片异常")

    return jsonify(errno=RET.OK, errmsg="OK", data={"image_url": constants.QINIU_DOMIN_PREFIX + file_name})
